/**
 * Instantiate robot controller and all needed modules
 *    
 * @author Sylvere Billout
 *
 */
package org.hypheli.testApps;


import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import android.content.Context;
import android.graphics.*;
import android.view.*;
import android.util.AttributeSet;
import android.util.Log;
import android.content.res.Resources;

import org.hh.common.GUIDispatcher;
import org.hh.common.Loader;
import org.hh.common.ScalpelRPCServer;
import org.hh.common.XMLHandler;

public class RobotView extends View{

	private Loader fLoader = null;
	private GUIDispatcher fGuiDispatcher = null;
	
	  private Paint textPaint;
	  private Paint fRobotPaint;
		
		ScalpelRPCServer fRpcServer;

		public boolean onTouch(MotionEvent event){
			if( fGuiDispatcher != null )
				fGuiDispatcher.onTouch(event);
			return true;
		}
	  
	  protected void initView() {
	  	
	    setFocusable(true);
	    
	    Resources r = this.getResources();

		  fRobotPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
	    fRobotPaint.setColor(r.getColor(R.color.background_color));
	    fRobotPaint.setStrokeWidth(1);
	    fRobotPaint.setStyle(Paint.Style.FILL_AND_STROKE);

	    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
	    textPaint.setColor(r.getColor(R.color.text_color));
	    

			try {
				
				/** Handling XML */
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();

				Resources res = getResources();
				InputStream xip = res.openRawResource(R.raw.worldmap);
			
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				XMLHandler myXMLHandler = new XMLHandler(getContext());
				sp.parse(xip, myXMLHandler);
				
				HashMap<String, Object> listObject = myXMLHandler.getAllObject();
				
				
				fRpcServer = new ScalpelRPCServer(listObject);
				
				new Thread(new Runnable() {
			    public void run() {
			    	fRpcServer.listen();
			    }
			  }).start();
				
				fGuiDispatcher = ((GUIDispatcher)listObject.get("world.guidispatcher"));
				if( fGuiDispatcher != null )
					fGuiDispatcher.initView(getContext());
				
				fLoader = ((Loader)listObject.get("world.loader"));
				if( fLoader != null )
					fLoader.onLoad();
				
			} catch (Exception e) {
				Log.e("RobotView", "XML Pasing Excpetion = " + e.toString());
			}
	  }
	  
	  @Override
	  protected void onDraw(Canvas canvas){
			if( fGuiDispatcher != null )
				fGuiDispatcher.onDraw(canvas, fRobotPaint);

	  }

	  public RobotView(Context context) {
	    super(context);
	    initView();
	  }

	  public RobotView(Context context, AttributeSet attrs) {
	    super(context, attrs);
	    initView();
	  }

	  public RobotView(Context context, 
	                     AttributeSet ats, 
	                     int defaultStyle) {
	    super(context, ats, defaultStyle);
	    initView();
	  }

	  public void finish() {
			fGuiDispatcher.finish();			
		}
}
